/*
 * video page
**/
<template>
<div class="fullx" v-cloak>
  <remote-js ref="mytvp"></remote-js>
	<div class="main">
		<div class="body" v-if="!friendid">
      <template v-if="!isPlayed">
        <h6 class="title">获取积分须知：</h6>
        <p class="desc">1.看完视频可获取 <span>{{score}}积分。</span></p>
        <p class="desc">2.点击右上角“...”进行分享可获得更多积分；</p>
        <p class="desc">3.分享每增加一次预览可获得<span>{{score}}积分</span>，最高收益可获得<span>{{score * 21}}积分</span>；</p>
      </template>
      <template v-else>
        <h6 class="title">积分状态：</h6>
        <p class="desc">1.您已看完视频并获得 <span>{{score}}</span>积分。去分享获取更多积分。</p>
        <p class="desc">2.您已经邀请了<span>{{scoreInfo.times}}</span>名好友，获得了<span>{{scoreInfo.score}}</span>积分。</p>
      </template>
      <i class="share"></i>
		</div>
		<div class="video-box" id="mod_player">
    </div>
		<div class="btn-box">
			<a class="btn orange" v-if="!friendid" @click="back">返回</a>
		</div>
	</div>
	<div class="layer" v-show="layershow">
		<div class="redbag"><span :class="{'on':scoreshow}">+{{score}}积分</span></div>
	</div>
</div>
</template>
<script>
import {getWZTInfo, getWZTScore, judgeReward, shareRecord} from 'src/service/getData'
import {mapState} from 'vuex'
export default {
  data () {
    return {
      geted: false, // 获取积分成功过
      isPlayed: false, // 是否完成播放任务
      videoUrl: '', // 视频链接地址
      t: null,
      friendid: '', // friendid
      appid: '',
      wzid: '',
      scoreInfo: {},
      score: 0, // 积分值
      dataInfo: {},
      layershow: false, // +积分
      scoreshow: false,
      backHomeQuery: '/index' // 跳转路由
    }
  },
  computed: {
    ...mapState([
      'I9RIA'
    ])
  },
  mounted () {
    setTimeout(() => {
      let query = this.$route.query
      if (!query.appid) query = this.makeQuery()
      this.appid = query.appid
      this.friendid = query.friendid ? query.friendid : ''
      this.score = query.score
      this.wzid = query.wzid
      this.loadTXVideo(query.token)
      this.initData(query)
    }, 0)
  },
  beforeDestroy () {
    if (this.t) {
      clearTimeout(this.t)
      this.t = null
    }
    this.setShare(false, {})
  },
  methods: {
    async initData (query) {
      let res = await getWZTInfo(this.appid)
      if (res.code === 0) {
        this.dataInfo = res.data
      }
      this.setShare(true, query)
      if (this.friendid) return
      let scoreInfo = await getWZTScore(this.appid, this.I9RIA.unionid)
      this.scoreInfo = scoreInfo.data
      if (scoreInfo.data.selfhas === 0) {
        this.isPlayed = false
      } else {
        this.isPlayed = true
      }
      this.setTimer()
    },
    loadTXVideo (token) {
      let self = this
      window.mytvp.onload = function () {
        self.initTXVideo(token)
      }
      if (window.tvp) {
        self.initTXVideo(token)
      }
    },
    initTXVideo (token) {
      let self = this
      let video = new window.tvp.VideoInfo()
      video.setVid(token) // 设置视频id
      let player = new window.tvp.Player()
      player.create({
        video: video,
        modId: 'mod_player',
        autoplay: false,
        pic: '',
        isHtml5UseAirPlay: true,
        isHtml5ShowPosterOnStart: true,
        isHtml5ShowPosterOnEnd: true,
        isHtml5ShowPosterOnChange: true,
        html5Preload: true,
        isHtml5ControlAlwaysShow: false,
        isiPhoneShowPosterOnPause: true,
        isiPhoneShowPlaysinline: true,
        plugins: {
          AppRecommend: true
        }
      })
      if (!self.isPlayed) { // 判断是否为一维用户且是否完成播放15秒的任务
        player.onplaying = function (vid) {
          self.setTimer()
        }
        player.onpause = function (vid) {
          clearTimeout(self.t)
          self.t = null
        }
        player.onresume = function (vid) {
          if (player.getPlaytime() < 15 && !self.isPlayed) {
            self.setTimer()
          }
        }
      }
    },
    async setTimer (code) {
      console.log('开始加分')
      if (this.geted) return
      this.geted = true
      if (localStorage[this.appid]) return
      var _url = location.origin + '/play/tpl_wxmppage/?wzid=' + this.wzid + '&friendid=' + this.friendid
      if (!code) {
        let start = await judgeReward(this.appid, this.I9RIA.unionid, encodeURIComponent(_url), '')
        this.geted = false
        if (!start.data.code) return
        if (start.data.canFlag !== 1) {
          this.isPlayed = true
          return
        }
        clearTimeout(this.t)
        this.t = setTimeout(() => {
          this.setTimer(start.data.code)
        }, 15000)
      } else {
        let end = await judgeReward(this.appid, this.I9RIA.unionid, encodeURIComponent(_url), code)
        this.geted = true
        if (end.data.code === 1 && !this.friendid) {
          localStorage[this.appid] = 'x'
          this.layershowfn()
        }
      }
    },
    setShare (iswzt, query) {
      var that = this
      var _url = location.origin + '/?wzid=' + query.wzid + '&appid=' + query.appid + '&icon=' + query.icon + '&token=' + query.token + '&friendid=' + this.I9RIA.unionid
      if (iswzt) {
        this.I9RIA.shareConfig.title = this.dataInfo.title
        this.I9RIA.shareConfig.imgUrl = query.icon
        this.I9RIA.shareConfig.link = _url + '#/video'
        this.I9RIA.shareConfig.desc = this.dataInfo.desc
        this.I9RIA.shareConfig.success = function () {
          shareRecord(that.appid, _url)
        }
      } else {
        this.I9RIA.shareConfig.title = '玩赚'
        this.I9RIA.shareConfig.link = location.origin
        this.I9RIA.shareConfig.imgUrl = location.origin + '/static/imgs/wi.jpg'
        this.I9RIA.shareConfig.desc = '玩游戏赢大奖，更多惊喜等你拿！和我一起玩赚吧~  '
        this.I9RIA.shareConfig.success = function () {}
      }
      console.log(this.I9RIA)
    },
    layershowfn () {
      this.layershow = true
      setTimeout(() => {
        this.scoreshow = true
      }, 100)
      setTimeout(() => {
        this.layershow = false
        this.scoreshow = false
      }, 1800)
      this.backHomeQuery += '?appid=' + this.appid + '&score=' + this.score // 成功加积分则在跳转时带上相应参数
    },
    back () {
      this.$router.push(this.backHomeQuery)
    },
    makeQuery () {
      var param = location.search.substr(1).split('&')
      var q = {}
      for (var i = 0; i < param.length; i++) {
        var pra = param[i].split('=')
        q[pra[0]] = pra[1]
      }
      return q
    }
  },
  components: {
    'remote-js': {
      render (createElement, cxt) {
        // 接口文档 http://v.qq.com/open/doc/tvpapi2.0.pdf
        return createElement(
          'script',
          {
            attrs: {
              type: 'text/javascript',
              src: 'http://imgcache.qq.com/tencentvideo_v1/tvp/js/tvp.player_v2.js',
              id: 'mytvp'
            }
          },
          cxt
        )
      }
    }
  }
}
</script>
<style scoped>
	.fullx{z-index:999;position: fixed;z-index: 1001;}
	.main{padding:0.11rem .15rem;overflow-y:auto;background:#fff;}

	.share{background:url(../../../assets/imgs/icon-share.png) no-repeat; background-size:100%;position: absolute; width: 0.6rem; height: 1.4rem; top: -0.04rem; right: 0.04rem;}
	.body{background:#efeff4;border-radius:8px;padding:0.11rem 0.13rem;margin-top: 0.1rem;}
	.body .desc{line-height:0.23rem;font-size: 0.1rem;color:#666;}
	.body .desc.sm{line-height: 0.15rem;}
	.body .desc label{color:#333;}
	.body .desc span{color:#fa7429;}
	.btn-box{margin-top:.04rem;text-align: center;position: absolute;left:0;bottom:.9rem;width:100%;}
	.btn-box .btn{width:1.1rem;line-height:0.35rem;font-size: 0.13rem;text-align: center;color:#fff;display: inline-block;border-radius:22px;margin:0 0.18rem;}
	.btn-box .btn.orange{background:#ffa200;}
    .video-box{background: #000;margin-top: 1rem;width:3.45rem;height:1.725rem;}
    .video-box video{width:100%}
    .layer{position: absolute; width: 100%; top: 0; left: 0; height: 100%; background: rgba(0,0,0,0.6);opacity:1;}
	.redbag{width: 2.1rem; height: 2.2rem;background:url(../../../assets/imgs/redbag.png) no-repeat;background-size: 100%;margin: 2rem auto;text-align: center;}
	.redbag span{color: #ffdd00; font-size: 0.3rem;position: relative;top:2rem;opacity:0;transition:all .3s ease-in-out;}
	.redbag span.on{opacity:1;top:1.3rem;}
</style>
